#!/bin/sh
set -e

. /usr/share/debconf/confmodule

file="$1"

db_get apt-setup/services-select
if ! echo "$RET" | grep -q updates; then
	exit
fi

if db_get mirror/codename && [ "$RET" ]; then
	codename="$RET"
	db_get mirror/suite
	suite="$RET"

	db_get mirror/protocol
	protocol="$RET"
	db_get mirror/$protocol/hostname
	host="$RET"
	db_get mirror/$protocol/directory
	directory="/${RET#/}"
else
	db_get cdrom/codename
	codename="$RET"
	db_get cdrom/suite
	suite="$RET"
fi

# To determine if non-free and contrib should be included, grep
# the file to see if they are listed in it.
dists="main"
for dist in contrib non-free; do
	if grep -q '^[^#]* '$dist $ROOT/etc/apt/sources.list.new; then
		dists="$dists $dist"
	fi
done

# Don't test mirror if no network selected in netcfg
echo "# ${codename}-updates, previously known as 'volatile'" >> $file

if  [ -n "$protocol" ] && [ -n "$host" ]; then
	echo "deb $protocol://${host}${directory} ${codename}-updates $dists" >> $file
else
	echo "# A network mirror was not selected during install.  The following entries" >> $file
	echo "# are provided as examples, but you should amend them as appropriate" >> $file
	echo "# for your mirror of choice." >> $file
	echo "#" >> $file
	echo "# deb http://deb.debian.org/debian/ ${codename}-updates $dists" >> $file
fi
if db_get netcfg/dhcp_options && \
   [ "$RET" = "Do not configure the network at this time" ]; then
	CODE=9
else
	CODE=0
	case $protocol in
	    http|https)
		export ASV_TIMEOUT="-o Acquire::$protocol::Timeout=30"
		;;
	esac
	if ! apt-setup-verify --from $PROGRESS_FROM --to $PROGRESS_TO $file; then
		db_subst apt-setup/service-failed HOST "$host"
		db_input critical apt-setup/service-failed || true
		if ! db_go; then
			exit 10 # back up
		fi
		CODE=9
	fi
fi

deb_src="deb-src"
db_get apt-setup/enable-source-repositories
if [ "$RET" = false ]; then
	deb_src="# deb-src"
fi

if [ -n "$protocol" ] && [ -n "$host" ]; then
	echo "$deb_src $protocol://${host}${directory} ${codename}-updates $dists" >> $file
else
	echo "# deb-src http://deb.debian.org/debian/ ${codename}-updates $dists" >> $file
fi

exit $CODE
